package sipus.action.master;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Center;
import org.zkoss.zul.Column;
import org.zkoss.zul.Columns;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.Rows;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.South;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbar;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sipus.action.master.helper.RevisiHelper;
import sipus.common.Common;
import sipus.common.CommonPrivilages;
import sipus.database.dao.AgamaDao;
import sipus.database.dao.DaoFactory;
import sipus.database.hibernate.HibernateUtil;
import sipus.database.model.Agama;


public class AgamaAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5779730267402400328L;
	private Window addWindow;
	private Grid grid;

	private Textbox searchnama;

	private Textbox nama;
	private Textbox keterangan;

	private boolean edit = false;
	private boolean delete = false;

	private Agama agama;
	private Toolbarbutton add;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		if (session.getAttribute("usersTemp") == null
				|| !CommonPrivilages.checkPrevilages(CommonPrivilages.READ)) {
			session.removeAttribute("usersTemp");
			execution.sendRedirect("/logoff");
			return;
		}

		add.setVisible(CommonPrivilages
				.checkPrevilages(CommonPrivilages.CREATE));
		add.setTooltiptext("Tambah");

		edit = CommonPrivilages.checkPrevilages(CommonPrivilages.UPDATE);
		delete = CommonPrivilages.checkPrevilages(CommonPrivilages.DELETE);
		onSearchDefault(null);
	}

	class AgamaRenderer implements RowRenderer {

		@Override
		public void render(final Row arg0, Object arg1) throws Exception {
			// TODO Auto-generated method stub
			final Agama agama = (Agama) arg1;

			RevisiHelper.createNewRevisi(Agama.class, agama, agama.getNama())
					.setParent(arg0);
			new Label(agama.getKeterangan()).setParent(arg0);

			Hbox toolbar = new Hbox();
			Toolbarbutton button = new Toolbarbutton("", "/img/edit.gif");
			button.setTooltiptext("Rubah Data");
			button.setVisible(edit);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					init(agama);
					addWindow.setVisible(true);
					addWindow.onModal();
				}

			});
			button.setParent(toolbar);

			button = new Toolbarbutton("", "/img/delete.gif");
			button.setTooltiptext("Hapus Data");
			button.setVisible(delete);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					Messagebox.show("Apakah yakin ingin menghapus data ini ?",
							"Question", Messagebox.OK | Messagebox.CANCEL,
							Messagebox.QUESTION, new EventListener() {

								@Override
								public void onEvent(Event event)
										throws Exception {
									int i = new Integer(event.getData()
											.toString());
									if (i == Messagebox.OK) {
										try {
											AgamaDao agamaDao = DaoFactory
													.getInstance()
													.getAgamaDao();
											agamaDao.delete(agamaDao
													.merge(agama));
											onSearchDefault(event);
										} catch (Exception e) {
											e.printStackTrace();
											Messagebox
													.show("Data ini tidak dapat dihapus .., karena berelasi dengan data lainnya, error-nya adalah sbagai berikut:"
															+ e.getMessage());
										}

									}

								}
							});

				}
			});
			button.setParent(toolbar);
			toolbar.setParent(arg0);
		}

	}

	public void onAdd(Event event) throws Exception {
		init(new Agama());
		addWindow.setVisible(true);
		addWindow.onModal();
	}

	private void init(Agama agama) {
		this.agama = agama;
		addWindow.setTitle("Pendataan Agama");
		Common.clear(addWindow);
		Borderlayout borderlayout = new Borderlayout();
		Center center = new Center();
		center.setParent(borderlayout);
		center.setFlex(true);
		Grid grid = new Grid();
		grid.setParent(center);
		grid.setWidth("100%");
		grid.setHeight("100%");
		// grid.setOddRowSclass("non-odd");
		Columns columns = new Columns ();
		columns.setParent(grid);
		
		Column column = new Column ();
		column.setParent (columns);
		column.setWidth("20%");
		
		
		column = new Column ();
		column.setParent (columns);
		column.setWidth("80%");
			
		

		Rows rows = new Rows();
		rows.setParent(grid);

		Row row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Nama Agama"));
		row.appendChild(nama = new Textbox(agama.getNama() == null ? "" : agama
				.getNama()));
		nama.setWidth("95%");

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Keterangan"));
		row.appendChild(keterangan = new Textbox(
				agama.getKeterangan() == null ? "" : agama.getKeterangan()));
		keterangan.setWidth("95%");keterangan.setRows(4);
		keterangan.setRows(4);

		South south = new South();
		south.setFlex(true);
		south.setParent(borderlayout);

		Toolbar toolbar = new Toolbar();
		toolbar.setHeight("30px");
		toolbar.setParent(south);
		Toolbarbutton cancel = new Toolbarbutton("Batal", "/img/cancel.gif");
		cancel.setTooltiptext("Tutup");
		cancel.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}
		});
		cancel.setParent(toolbar);
		Toolbarbutton save = new Toolbarbutton("Simpan", "/img/save.gif");
		save.setTooltiptext("Simpan");
		save.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (onSave(event)) {
					onSearchDefault(null);
					addWindow.setVisible(false);
				}
			}
		});
		save.setParent(toolbar);
		borderlayout.setParent(addWindow);

	}

	public boolean onSave(Event event) throws Exception {
		if (nama.getValue().trim().equals("")) {
			Messagebox.show("Nama Agama harus diisi", "Peringatan",
					Messagebox.OK, Messagebox.EXCLAMATION);
			return false;
		}

		/*
		 * if (keterangan.getValue().trim().equals("")) {
		 * Messagebox.show("Keterangan harus diisi", "Peringatan",
		 * Messagebox.OK, Messagebox.EXCLAMATION); return false; }
		 */

		boolean i = checkNamaAgama();
		if (i) {
			Messagebox.show("Nama Agama sudah ada di database", "Peringatan",
					1, Messagebox.EXCLAMATION);
			return false;
		}

		AgamaDao agamaDao = DaoFactory.getInstance().getAgamaDao();
		if (agama.getId() != null) {
			agama = agamaDao.load(agama.getId());

		}

		agama.setNama(nama.getValue());
		agama.setKeterangan(keterangan.getValue());

		if (agama.getId() != null) {
			agamaDao.update(agama);
		} else {
			agamaDao.save(agama);
		}

		return true;
	}

	@SuppressWarnings("unchecked")
	public void onSearchDefault(Event event) {
		Session session = HibernateUtil.currentSession();
		List<Agama> agama = session
				.createCriteria(Agama.class)
				.addOrder(Order.desc("id"))
				.add(Restrictions.ilike("nama", searchnama.getValue(),
						MatchMode.ANYWHERE)).setMaxResults(Common.MAX_RESULT)
				.list();
		ListModel strset = new SimpleListModel(agama);
		grid.setRowRenderer(new AgamaRenderer());
		grid.setModel(strset);

		grid.renderAll();
		// grid.setOddRowSclass("non-odd");

	}

	public Boolean checkNamaAgama() {

		Integer kotaCount = null;
		Session session = HibernateUtil.currentSession();
		kotaCount = ((Number) session
				.createCriteria(Agama.class)
				.setProjection(Projections.count("id"))
				.add(Restrictions.eq("nama", nama.getValue().trim()))
				.add(this.agama.getId() == null ? Restrictions
						.sqlRestriction("1=1") : Restrictions.ne("id",
						this.agama.getId())).uniqueResult()).intValue();

		return !kotaCount.equals(0);
	}

}
